package com.space.school.controller;

import com.space.school.domain.Category;
import com.space.school.domain.ProductInfo;
import com.space.school.services.ProductInfoService;
import com.space.school.services.impl.ProductInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@WebServlet(name = "productInfoOperateServlet",value = "/productInfoOperateServlet")
public class ProductInfoOperateServlet extends HttpServlet {
    private ProductInfoService productInfoService = new ProductInfoServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String product_id = req.getParameter("product_id");
        String operate = req.getParameter("operate");
        int id=0;
        if(product_id!=null){
            id=Integer.parseInt(product_id);
        }
        List<Category> categoryList=productInfoService.findAll();
        if(operate.equals("add")){
            req.setAttribute("categoryList",categoryList);
            req.getRequestDispatcher("insertProductInfo.jsp").forward(req,resp);
        }else if(operate.equals("update")){
//            查询修改信息
            ProductInfo productInfo=productInfoService.findById(id);
            req.setAttribute("product",productInfo);
//            商品类目下拉菜单
            req.setAttribute("categoryList",categoryList);
//            跳转页面
            req.getRequestDispatcher("updateProductInfo.jsp").forward(req,resp);

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String product_id = req.getParameter("product_id");
        if(product_id!=null){
//            修改操作
            Map<String,String[]>map=req.getParameterMap();
            productInfoService.update(map);
        }else {
            //            为新增操作
            ProductInfo productInfo=new ProductInfo();
            productInfo.setProduct_name(req.getParameter("product_name"));
            productInfo.setProduct_price(Integer.parseInt(req.getParameter("product_price")));
            productInfo.setProduct_stock(Integer.parseInt(req.getParameter("product_stock")));
            productInfo.setProduct_description(req.getParameter("product_description"));
            productInfo.setProduct_icon(req.getParameter("product_icon"));
            productInfo.setProduct_status(Integer.parseInt(req.getParameter("product_status")));
            productInfo.setCategory_type(Integer.parseInt(req.getParameter("category_type")));
            productInfoService.save(productInfo);
        }
        resp.sendRedirect("/productInfoServlet");
    }
}
